package com.kl.drs.dataSource;

import java.io.IOException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.kl.drs.util.Log4jUtils;

@Configuration
@MapperScan(basePackages = {"com.kl.drs.mapper.core"}, sqlSessionFactoryRef = "sqlSessionFactoryCORE")
public class MybatisCOREConfig {
	
	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

	@Bean(name = "dataSourceCORE")
	@ConfigurationProperties(prefix = "spring.datasource.core")
	public DataSource dataSourceCORE() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "transactionManagerCORE")
	public DataSourceTransactionManager transactionManagerCORE(
			@Qualifier("dataSourceCORE") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean("sqlSessionFactoryCORE")
	public SqlSessionFactory sqlSessionFactoryCORE(
			@Qualifier("dataSourceCORE") DataSource core){
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		SqlSessionFactory sqlSessionFactory = null;
		factoryBean.setDataSource(core); // 使用core数据源, 连接core库
		factoryBean.setTypeAliasesPackage("com.kl.drs.bean.bo");
		try {
			factoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
			sqlSessionFactory = factoryBean.getObject();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log4jUtils.logError("MybatisCOREConfig.sqlSessionFactoryCORE", "Error while getResources 'classpath:/mapper/*.xml'", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log4jUtils.logError("MybatisCOREConfig.sqlSessionFactoryCORE", "Error while factoryBean.getObject()", e);
		}
		return sqlSessionFactory;

	}
	@Bean("sqlSessionTemplateCORE")
	public SqlSessionTemplate sqlSessionTemplateCORE(
			@Qualifier("sqlSessionFactoryCORE") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}